package net.sinmetal.twitcockpit.service;

import org.slim3.datastore.Datastore;

import net.sinmetal.twitcockpit.meta.RobotMeta;
import net.sinmetal.twitcockpit.model.Robot;

import com.google.appengine.api.datastore.Key;

/**
 * RobotService
 *
 * @author Sinmetal
 *
 */
public class RobotService {

    private RobotMeta meta = RobotMeta.get();

    /**
     * DatastoreにModelをputする
     *
     * @param robot
     * @return
     */
    public Key put(Robot robot) {
        Key key = Robot.createKey(robot.getTwitterScreenName());
        Robot stored = Datastore.getOrNull(meta, key);
        if (stored != null) {
            if (!stored.getTwitterId().equals(robot.getTwitterId())) {
                String error =
                    String.format(
                        "TwitterID not equals:stored=%s,argment=%s",
                        stored.getTwitterId(),
                        robot.getTwitterId());
                throw new RuntimeException(error);
            }
        }
        robot.setKey(key);
        return Datastore.put(robot);
    }

    /**
     * DatastoreからRobotModelをgetする
     *
     * @param twitterScreenName
     * @return
     */
    public Robot get(String twitterScreenName) {
        Key key = Robot.createKey(twitterScreenName);
        return Datastore.get(meta, key);
    }
}
